import cv2

if __name__ == '__main__':
    # 1. 图片输入
    image_np = cv2.imread('xiaoren.jpg')

    # 2. 灰度化
    image_np_grey = cv2.cvtColor(
        image_np,  # 要转换的图像
        cv2.COLOR_BGR2GRAY  # BGR→灰度
    )

    # 3. 自适应二值化
    maxval = 255
    ret, image_np_thresh = cv2.threshold(
        image_np_grey,
        127,
        maxval,
        cv2.THRESH_BINARY
    )

    # 4. 形态学操作
    # 创建核
    kernel = cv2.getStructuringElement(
        cv2.MORPH_RECT,  # 核的形状
        (3, 3)  # 核的尺寸
    )
    print(kernel)


    # 腐蚀使用erode函数，膨胀使用dilate函数
    # morph_image = cv2.dilate(
    #     image_np_thresh,  # 二值化图像
    #     kernel,  # 核
    #     )

    morph_image1 = cv2.erode(
        image_np_thresh,  # 二值化图像
        kernel,  # 核
        iterations=3
    )



    # 5. 图片输出
    cv2.imshow('morph_image1', morph_image1)
    cv2.imwrite('morph_image1.jpg',morph_image1)
    cv2.waitKey(0)